/**
 * @fileOverview
 */

/**
 * @class
 */
Karamu = Karamu || {};
Karamu.Controllers = Karamu.Controllers || {};

/**
 * @class
 * @requires jQuery, underscore.js, karamu.js
 * @param {Object} context the top-level controller object, e.g karamu
 */
Karamu.Controllers.Desktop = function(context){
    this.context = context;

    this.renderGroups = function(element, groups){
        $(element).empty();
        _.each(groups, function(group) {
            this.context.controllers.group.render(group);
        }, this);
    };

    this.renderSidebar = function(element, group){
        $(element).empty();
        if (group && group.gadgets) {
            _.each(group.gadgets, function(gadget){
                this.context.controllers.shortcut.renderSidebar(element, gadget);
            }, this);
        }
    };

    this.windowCount = 0;

    this.startMenu = function(e){
        e.preventDefault();

        // Allow overlay to cover flash elements
        $('object').attr('wmode', 'opaque');

        $('#overlay').toggle('size', {origin: 'top'}, 250, function(){});
    };

    this.addGroup = function(e) {
        e.preventDefault();
        var group = $.extend(true, {}, e.data.models[e.data.view]._group);
        e.data.getGUID({
            context: e.data,
            success: function(xml){
                group.id = $('guid', xml).text();
            },
            error: function(){
                if (console && console.log) console.log('Error retrieving GUID.');
            },
            complete: function(){
                // Render, then update the model in the background
                this.controllers.group.render(group);
                $(this.models[this.view]).trigger('add-group', group);
            }
        });
    };

    // Search for gadgets. If a gadget is within the group, display. Otherwise hide. Case insensitive.
    this.search = function(e){
        var query = $('#search').val();
        // Something in the search
        if (query.length > 0) {
            var keywords = query.toLowerCase().split(' ');
            $('.group').each(function(groupIndex, group){
                var found = false;
                $(e.data.controllers.catalog.options.gadgetSelector, group).each(function(gadgetIndex, gadget) {
                    var gadgetName = $(gadget).data('title');
                    for (var i = 0, j = keywords.length; i < j; i++) {
                        var re = new RegExp('.*' + keywords[i] + '.*', 'i');
                        if (re.test(gadgetName)) {
                            found = true;
                        }
                    }
                });
                // If found, show. Hide otherwise
                if (found) $(group).show();
                else       $(group).hide();
            });
        } else {
            $('.group').each(function(groupIndex, group){
                $(group).show();
            });
        }
    }
};